package com.laicunba.ext.listener;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.laicunba.ext.service.SlaveQueryService;
import com.laicunba.jms.JmsQueueListenerTemplate;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.service.MobileMessageService;
import com.laicunba.service.TemplateService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

@Component
public class CouponExpiredNoticeJob extends JmsQueueListenerTemplate {

	@Autowired
	private SlaveQueryService slaveQueryService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private MobileMessageService mobileMessageService;

	@Override
	public String queue() {
		return "lcb.core.action.coupon.expired.notice";
	}

	@Override
	public boolean receive(Message msg) {

		if (CacheUtil.incr("sys.incr.job.CouponExpiredNoticeJob", 6000) > 1) {
			return true;
		}

		TemplateDO cashTmp = templateService.findByCodeWidthDefault("CASH_COUPON_WILL_EXPIRE");
		TemplateDO rateTmp = templateService.findByCodeWidthDefault("RATE_COUPON_WILL_EXPIRE");
		Date tomorrow = new Date();
		tomorrow.setDate(tomorrow.getDate() + 1);
		String date = DateUtil.formatDate(tomorrow);
		List<Map<String, Object>> datas = slaveQueryService.query("SLAVE_COUPON.findWillExpiredCoupons", new HashMap());
		String messageContent = null;
		String mobile = null;
		int sendCount = 0;
		for (Map<String, Object> map : datas) {
			mobile = (String) map.get("mobile");
			if (StringUtil.isEmpty(mobile)) {
				continue;
			}
			map.put("date", date);
			messageContent = "cash".equalsIgnoreCase((String) map.get("type")) ? templateService.simpleMerge(cashTmp.getContent(), map) : templateService.simpleMerge(rateTmp.getContent(), map);
			mobileMessageService.sendMsgAsync(mobile, messageContent);
			sendCount++;
		}
		mobileMessageService.sendMsgAsync("18367156949", String.format("有%s张券即将过期，已短信通知用户", sendCount));
		return true;
	}

}
